using System;
using System.Threading.Tasks;
using Windows.ApplicationModel;

namespace Xiaowei.Services
{
    public static class StartupService
    {
        public static event EventHandler StartupStateChanged;

        static bool _autoRetrive = false;
        public static bool AutoRetrieve
        {
            get { return _autoRetrive; }
            set
            {
                if (_autoRetrive != value)
                {
                    _autoRetrive = value;
                    if (_autoRetrive)
                    {
                        AutoUpdate();
                    }
                }
            }
        }
        static StartupTask task = null;
        public static async void Init()
        {
            task =  await StartupTask.GetAsync("XiaoweiRun");
            Retrieve();
        }

        public static async void RunAsync()
        {
            if (!AutoStartUp)
            {
                await task.RequestEnableAsync();
            }
            else
            {
                task.Disable();
            }
            StartupStateChanged?.Invoke(null, EventArgs.Empty);
        }

        public static bool AutoStartUp
        {
            get
            {
                return task.State == StartupTaskState.Enabled || task.State == StartupTaskState.EnabledByPolicy;
            }
        }

        public static bool StartUpDisabledByUser
        {
            get
            {
                return task.State == StartupTaskState.DisabledByUser;
            }
        }

        private static StartupTaskState startupTaskState = StartupTaskState.Disabled;

        public static StartupTaskState StartupTaskState
        {
            get
            {
                return startupTaskState;
            }
            set
            {
                if(startupTaskState!=value)
                {
                    startupTaskState = value;
                    StartupStateChanged?.Invoke(null,EventArgs.Empty);
                }
            }
        }
        private static void Retrieve()
        {
            StartupTaskState = task.State;
        }

        private static async void AutoUpdate()
        {
            await Task.Run(async () =>
            {
                while (_autoRetrive)
                {
                    Retrieve();
                    await Task.Delay(TimeSpan.FromMilliseconds(1000)).ConfigureAwait(false);
                }
            }).ConfigureAwait(false);
        }
    }
}
